package com.example.weatherapp1.presentation.viewmodel


import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.weatherapp1.data.model.City
import com.example.weatherapp1.data.model.SavedWeather
import com.example.weatherapp1.data.model.WeatherResponse
import com.example.weatherapp1.data.repository.WeatherRepository
import com.example.weatherapp1.domain.service.LocationService
import com.example.weatherapp1.domain.service.WeatherService
import com.example.weatherapp1.domain.usecase.GetWeatherForCityUseCase
import com.example.weatherapp1.domain.usecase.GetWeatherForCurrentLocationUseCase
import dagger.hilt.android.lifecycle.HiltViewModel

import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject


@HiltViewModel
class WeatherViewModel @Inject constructor(
    private val weatherRepository: WeatherRepository,
    private val weatherService: WeatherService,
    private val locationService: LocationService,
    private val getWeatherForCurrentLocationUseCase: GetWeatherForCurrentLocationUseCase,
    private val getWeatherForCityUseCase: GetWeatherForCityUseCase
) : BaseViewModel() {

    // 天气数据
    private val _weatherData = MutableLiveData<WeatherResponse?>()
    val weatherData: LiveData<WeatherResponse?> = _weatherData

    // 当前选中的城市
    private val _selectedCity = MutableLiveData<City?>()
    val selectedCity: LiveData<City?> = _selectedCity

    // 城市列表
    val cities = weatherRepository.getAllCities()

    // 加载状态
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading

    // 错误信息
    private val _errorMessage = MutableLiveData<String?>()
    val errorMessage: LiveData<String?> = _errorMessage

    // 当前城市的最新天气
    private var _currentCityWeather = MutableLiveData<SavedWeather?>()

    init {
        // 尝试加载当前位置的天气
        loadCurrentLocationWeather()
    }

    // 加载当前位置的天气
    fun loadCurrentLocationWeather() {
        _isLoading.value = true
        _errorMessage.value = null

        launchSafe {
            val weatherResponse = getWeatherForCurrentLocationUseCase()
            _weatherData.value = weatherResponse

            if (weatherResponse != null) {
                val currentCity = weatherRepository.getCurrentLocationCity()
                _selectedCity.value = currentCity
                currentCity?.let { observeCityWeather(it.id) }
            } else {
                _errorMessage.value = "无法获取当前位置天气数据"
            }

            _isLoading.value = false
        }
    }

    // 加载指定城市的天气
    fun loadCityWeather(city: City) {
        _isLoading.value = true
        _errorMessage.value = null
        _selectedCity.value = city

        launchSafe {
            try {
                val weatherResponse = getWeatherForCityUseCase(city)
                _weatherData.value = weatherResponse
                observeCityWeather(city.id)
            } catch (e: Exception) {
                _errorMessage.value = "获取天气失败: ${e.message}"
            } finally {
                _isLoading.value = false
            }
        }
    }

    // 观察城市的天气变化
    private fun observeCityWeather(cityId: Int) {
        viewModelScope.launch {
            weatherRepository.getLatestWeatherByCityId(cityId).collectLatest { savedWeather ->
                _currentCityWeather.value = savedWeather
                savedWeather?.let {
                    _weatherData.value = weatherService.parseSavedWeather(it)
                }
            }
        }
    }

    // 添加新城市
    fun addCity(city: City) {
        launchSafe {
            weatherRepository.addCity(city)
        }
    }

    // 删除城市
    fun deleteCity(cityId: Int) {
        launchSafe {
            weatherRepository.deleteCity(cityId)
            // 如果删除的是当前选中的城市，重置选择
            if (_selectedCity.value?.id == cityId) {
                _selectedCity.value = null
                _weatherData.value = null
                // 尝试加载当前位置的天气
                loadCurrentLocationWeather()
            }
        }
    }

    // 检查定位权限
    fun hasLocationPermission(): Boolean {
        return locationService.hasLocationPermission()
    }

    // 解析天气状态为图标
    fun getWeatherIcon(skyCon: String): Int {
        return weatherService.getWeatherIcon(skyCon)
    }

    // 解析天气状态为文字描述
    fun getWeatherDescription(skyCon: String): String {
        return weatherService.getWeatherDescription(skyCon)
    }
}
